<template>
    <div class="container">
        <Breadcrumb
            :items="[
                'menu.device',
                'menu.device.product',
                'menu.device.product.detail',
            ]"
        />
        <a-space direction="vertical" :size="16" fill>
            <a-card class="general-card">
                <detail-item
                    :data="productInfoData"
                    :title="$t('product.info')"
                    :loading="productInfoLoading"
                    :label-style="{
                        width: '120px',
                        textAlign: 'right',
                        paddingRight: '24px',
                    }"
                    layout="inline-horizontal"
                ></detail-item>
            </a-card>
            <a-card class="general-card" hoverable style="padding: 20px 0 0">
                <a-tabs type="rounded" default-active-key="1">
                    <a-tab-pane
                        key="1"
                        class="detail-tab-pane"
                        :title="$t('chan-pin-shu-xing')"
                    >
                        <div
                            style="
                                display: flex;
                                justify-content: flex-end;
                                margin-bottom: 12px;
                            "
                        >
                            <a-button
                                type="primary"
                                @click="openModelDialog('ADD', undefined)"
                            >
                                {{ $t('xin-zeng-shu-xing') }}
                            </a-button>
                        </div>
                        <a-table
                            row-key="id"
                            :loading="tableConfig.loading"
                            :columns="tableConfig.columns"
                            :data="tableConfig.data"
                            :bordered="false"
                        >
                            <template #operations="{ record }">
                                <a-button
                                    type="text"
                                    size="small"
                                    @click="openModelDialog('EDIT', record.id)"
                                >
                                    {{ $t('edit') }}
                                </a-button>
                                <a-popconfirm
                                    :content="
                                        $t(
                                            'que-ren-shi-fou-shan-chu-gai-shu-xing'
                                        )
                                    "
                                    type="warning"
                                    @ok="deleteModelProp(record.id)"
                                >
                                    <a-button type="text" size="small">
                                        {{ $t('delete') }}
                                    </a-button>
                                </a-popconfirm>
                            </template>
                        </a-table>
                    </a-tab-pane>
                    <a-tab-pane
                        key="2"
                        class="detail-tab-pane"
                        title="告警配置"
                    >
                        <div
                            style="
                                display: flex;
                                justify-content: flex-end;
                                margin-bottom: 12px;
                            "
                        >
                            <a-button
                                type="primary"
                                @click="openAlertDialog('ADD', undefined)"
                            >
                                新增
                            </a-button>
                        </div>
                        <a-table
                            row-key="id"
                            :loading="alertTableConfig.loading"
                            :columns="alertTableConfig.columns"
                            :data="alertTableConfig.data"
                            :bordered="false"
                        >
                            <template #operations="{ record }">
                                <a-button
                                    type="text"
                                    size="small"
                                    @click="openAlertDialog('EDIT', record.id)"
                                >
                                    {{ $t('edit') }}
                                </a-button>
                                <a-popconfirm
                                    content="确认删除该该告警吗?"
                                    type="warning"
                                    @ok="deleteAlert(record.id)"
                                >
                                    <a-button type="text" size="small">
                                        {{ $t('delete') }}
                                    </a-button>
                                </a-popconfirm>
                            </template>
                        </a-table>
                    </a-tab-pane>
                </a-tabs>
            </a-card>
        </a-space>
        <ModelDialog
            :id="modelDialogConfig.type === 'EDIT' ? modelDialogConfig.id : ''"
            ref="modelDialogRef"
            :type="modelDialogConfig.type"
            :title="modelDialogConfig.title"
            :product-id="query.id"
            @submit="fetchProductModelData"
        >
        </ModelDialog>
        <DialogAlert
            :id="alertDialogConfig.type === 'EDIT' ? alertDialogConfig.id : ''"
            ref="dialogAlertRef"
            :type="alertDialogConfig.type"
            :title="alertDialogConfig.title"
            :product-id="query.id"
            @submit="fetchProductAlertData"
        >
        </DialogAlert>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, nextTick } from 'vue';
    import { get } from 'lodash';
    import { useRoute } from 'vue-router';
    import useLoading from '@/hooks/loading';
    import { useI18n } from 'vue-i18n';
    import DetailItem from '@/components/detail-item.vue';
    import ModelDialog from './model-dialog.vue';
    import DialogAlert from './dialog-alert.vue';
    import {
        getProductInfo,
        getProductModelList,
        deleteProductModel,
        productAlertDetail,
        productAlertList,
        editProductAlert,
        addProductAlert,
        deleteProductAlert,
    } from './service';
    import {
        ProductCategoryDict,
        ProductTypeDict,
        StatusDict,
        DATA_TYPE_OPTIONS,
        AlertStatusDict,
    } from './const';

    const { t } = useI18n();
    const { loading: productInfoLoading, setLoading: setProductInfoLoading } =
        useLoading(true);
    const { query } = useRoute();
    const modelDialogRef = ref();
    const modelDialogConfig = reactive({
        type: 'ADD',
        id: undefined,
        title: t('product.create.title'),
    });
    const dialogAlertRef = ref();
    const alertDialogConfig = reactive({
        type: 'ADD',
        id: undefined,
        title: '新建',
    });

    const tableConfig = reactive({
        loading: false,
        columns: [
            {
                title: t('shu-xing-ming-cheng'),
                dataIndex: 'name',
            },
            {
                title: t('product.model.flag'),
                dataIndex: 'identifier',
            },
            {
                title: t('product.model.dataType'),
                dataIndex: 'datatype',
                render({ record }) {
                    return DATA_TYPE_OPTIONS.find(
                        (item) => item.value === record.datatype
                    )?.label;
                },
            },
            {
                title: t('shun-xu'),
                dataIndex: 'sort',
            },
            {
                title: 'icon',
                dataIndex: 'icon',
            },
            {
                title: t('device.create.time'),
                dataIndex: 'createTime',
            },
            {
                title: t('geng-xin-shi-jian'),
                dataIndex: 'updateTime',
            },
            {
                title: t('operation'),
                dataIndex: 'operations',
                width: 180,
                slotName: 'operations',
            },
        ],
        data: [],
    });
    const alertTableConfig = reactive({
        loading: false,
        columns: [
            {
                title: '告警名称',
                dataIndex: 'alertName',
            },
            {
                title: '状态',
                dataIndex: 'status',
                render({ record }) {
                    return AlertStatusDict[record.status];
                },
            },
            {
                title: t('device.create.time'),
                dataIndex: 'createTime',
            },
            {
                title: t('geng-xin-shi-jian'),
                dataIndex: 'updateTime',
            },
            {
                title: t('operation'),
                dataIndex: 'operations',
                width: 180,
                slotName: 'operations',
            },
        ],
        data: [],
    });

    const productInfoData = ref([
        {
            label: t('chan-pin-bian-hao'),
            path: 'productNo',
            value: '',
        },
        {
            label: t('product.name'),
            path: 'productName',
            value: '',
        },
        {
            label: t('product.type'),
            path: 'productCategory',
            formatter(val: string) {
                return ProductCategoryDict[val];
            },
            value: '',
        },
        {
            label: t('device.type'),
            path: 'productType',
            formatter(val: string) {
                return ProductTypeDict[val];
            },
            value: '',
        },
        {
            label: t('description'),
            path: 'description',
            value: '',
        },
        {
            label: t('status'),
            path: 'status',
            formatter(val: 0 | 1) {
                return StatusDict[val];
            },
            value: '',
        },
    ]);

    function openModelDialog(type: 'ADD' | 'EDIT', id: string | undefined) {
        modelDialogConfig.type = type;
        modelDialogConfig.id = id;
        modelDialogConfig.title = t('xin-zeng-shu-xing');
        if (type === 'EDIT') {
            modelDialogConfig.title = t('bian-ji-shu-xing');
            modelDialogConfig.id = id;
        }
        // 更新数据后再打开弹窗
        nextTick(() => {
            modelDialogRef.value.open();
        });
    }

    async function deleteModelProp(id: string) {
        await deleteProductModel({ id });
        // eslint-disable-next-line no-use-before-define
        fetchProductModelData();
    }

    function openAlertDialog(type: 'ADD' | 'EDIT', id: string | undefined) {
        alertDialogConfig.type = type;
        alertDialogConfig.id = id;
        alertDialogConfig.title = '新增';
        if (type === 'EDIT') {
            modelDialogConfig.title = '编辑';
            alertDialogConfig.id = id;
        }
        // 更新数据后再打开弹窗
        nextTick(() => {
            dialogAlertRef.value.open();
        });
    }
    /**
     *  删除告警
     * @param id
     */
    async function deleteAlert(id: string) {
        await deleteProductAlert({ id });
        // eslint-disable-next-line no-use-before-define
        fetchProductAlertData();
    }

    const fetchProductInfoData = async () => {
        try {
            const data = await getProductInfo({ id: query.id });
            productInfoData.value.forEach((item) => {
                const value = get(data.result, item.path);
                item.value = item.formatter ? item.formatter(value) : value;
            });
        } finally {
            setProductInfoLoading(false);
        }
    };
    fetchProductInfoData();

    const fetchProductModelData = async () => {
        try {
            tableConfig.loading = true;
            const data = await getProductModelList({ productId: query.id });
            tableConfig.data = data.result || [];
        } finally {
            tableConfig.loading = false;
        }
    };
    fetchProductModelData();
    // 告警
    const fetchProductAlertData = async () => {
        try {
            alertTableConfig.loading = true;
            const data = await productAlertList({ productId: query.id });
            alertTableConfig.data = data.result || [];
        } finally {
            alertTableConfig.loading = false;
        }
    };
    fetchProductAlertData();
</script>

<style scoped lang="less">
    .container {
        padding: 0 20px 20px;
    }

    .item-container {
        padding-top: 20px;

        :deep(.arco-descriptions-item-label) {
            font-weight: normal;
        }
    }

    .detail-tab-pane {
        padding: 0 20px 10px;
    }
</style>
